/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.wsinfra.wsrm.storage.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Date;

import cgl.narada.wsinfra.schemas.addressing.EndpointReferenceType;
import cgl.narada.wsinfra.util.MarshallingUtils;
import cgl.narada.wsinfra.wsrm.WsrmProcessingFactory;
import cgl.narada.wsinfra.wsrm.WsrmSequencePolicies;
import cgl.narada.wsinfra.wsrm.WsrmSequencePolicyFactory;
import cgl.narada.wsinfra.wsrm.storage.WsrmSequenceInfo;

/** This interface encapsulates information pertaining to a sequence. These 
    include, 
    <br>(a) Its creation date
    <br>(b) Its Sequence Identifier and the addressing identifier 
    <br>(c) The addressing identifier associated with the sequence creation 
    request. The addressing identifier is different for different messages in 
    a sequence. But sequence creation requests and responses, acknowledgement 
    on the last message in a sequence, and finally the termination of a 
    sequence all carry the same addressing identifier.
    
    @author Shrideep Pallickara and Sangmi Lee
    $Date: 2005/07/29 22:41:31 $
    $Revision: 1.4 $
*/

public class WsrmSequenceInfoImpl implements WsrmSequenceInfo {

  private Date creationDate;
  private String sequenceIdentifier;
  private String addressingIdentifier;
  private boolean isSource = true;

  private EndpointReferenceType source;
  private EndpointReferenceType destination;

  private boolean hasWsrmSequencePolicies=false;
  private WsrmSequencePolicies wsrmSequencePolicies;

  private boolean hasLastMessageInfo=false;
  private long lastMessageNumber;
  
  private boolean isExpired = false;
  private boolean isTimedOut = false;
  private long timeOfLastActivity;
  private long timeoutTimestamp;


  private boolean isTerminated = false;
  private long terminationTimestamp;
  private String terminationReason;
  private MarshallingUtils marshaller = MarshallingUtils.getInstance();
  private WsrmSequencePolicyFactory wsrmSequencePolicyFactory =
  WsrmProcessingFactory.getWsrmSequencePolicyFactory();

  private String moduleName = "WsrmSequenceInfoImpl: ";

  public WsrmSequenceInfoImpl(Date creationDate, String sequenceIdentifier,
			      String addressingIdentifier, 
			      EndpointReferenceType source, 
			      EndpointReferenceType destination, 
			      boolean isSource) {
    this.creationDate = creationDate;
    this.sequenceIdentifier = sequenceIdentifier;
    this.addressingIdentifier = addressingIdentifier;
    this.source = source;
    this.destination = destination;
    this.isSource = isSource;
  }

  /** Retrieve the creation date for the sequence */
  public Date getCreationDate() {
    return creationDate;
  }
  
  
  /** Retrieve the sequence identifier. */
  public String getSequenceIdentifier() {
    return sequenceIdentifier;
  }
  
  
  /** Retrieve the addressing identifier. More specifically this refers to the
      addressing identifier associated with the sequence creation request. The
      addressing identifier is different for different messages within a 
      sequence. But sequence creation requests and responses, acknowledgement 
      on the last message in a sequence, and finally the termination of a 
      sequence all carry the same addressing identifier. */
  public String getAddressingIdentifier() {
    return addressingIdentifier;
  }
  

   /** Returns the source of this sequence */
  public EndpointReferenceType getSource() {
    return source;
  }

  /** Returns the destination of this sequence */
  public EndpointReferenceType getDestination() {
    return destination;
  }

  /** Checks if this node is the source of the sequence in question*/
  public boolean isSource() {
    return isSource;
  }


  /** Checks if this node is the destination of the sequence in question */
  public boolean isDestination() {
    if (isSource) {
      return false;
    }
    return true;
  }


  /** Check if there is a policy attachment */
  public boolean hasWsrmSequencePolicies() {
    return hasWsrmSequencePolicies;
  }

  /* Retrieve the policy attachment associated with the sequence */
  public WsrmSequencePolicies getWsrmSequencePolicies() {
    return wsrmSequencePolicies;
  }
  
  public void 
    setWsrmSequencePolicies(WsrmSequencePolicies wsrmSequencePolicies) {
    this.wsrmSequencePolicies = wsrmSequencePolicies;
    
    if (wsrmSequencePolicies != null) {
      hasWsrmSequencePolicies=true;
    } else {
      hasWsrmSequencePolicies=false;
    }
    
  }


  /** Check to see if we have information regarding the last message of a 
      sequence. */
  public boolean hasLastMessageInfo() {
    return hasLastMessageInfo;
  }
  
  /** If we do have information regarding the last message of a sequence,
      proceed to retrieve it */
  public long getLastMessageNumber() {
    return lastMessageNumber;
  }

  public void setLastMessageNumber(long lastMessageNumber) {
    this.lastMessageNumber = lastMessageNumber;
    if (lastMessageNumber == 0) {
      hasLastMessageInfo = false;
    } else {
      hasLastMessageInfo = true;
    }
  }

  /** Checks to see if the sequence has expired */
  public boolean isExpired() {
    return isExpired;
  }
  
  public void setExpired() {
    isExpired= true;
  }
  
  
  /** Checks to see if the sequence is timed out */
  public boolean isTimedOut() {
    return isTimedOut;
  }
  

  /** Retrieve the time associated with the last activity */  
  public long getTimeOfLastActivity() {
    return timeOfLastActivity;
  }


  public void setTimeOfLastActivity(long timeOfLastActivity) {
    this.timeOfLastActivity = timeOfLastActivity;
  }

  public void setTimedOut() {
    isTimedOut = true;
    timeoutTimestamp = System.currentTimeMillis();
  }

  /** Retrieve the timeout timestamp */
  public long getTimeoutTimestamp() {
    return timeoutTimestamp;
  }
  

   /** Check to see if the sequence is terminated */
  public boolean isTerminated() {
    return isTerminated;
  }
  
  
  /** Retrieve the termination timestamp */
  public long getTerminationTimestamp() {
    return terminationTimestamp;
  }

  
  /** Get the reason for termination */
  public String getTerminationReason() {
    return terminationReason;
  }

  public void setTermination(String reason) {
    isTerminated = true;
    terminationTimestamp = System.currentTimeMillis();
    terminationReason = reason;
  }

  /** Get a byte representation of the WsrmSequenceInfo */
  public byte[] getBytes() {
    ByteArrayOutputStream baOutputStream = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(baOutputStream);
    byte[] marshalledBytes= null;
    try {
      boolean hasCreationDate = false;
      if (creationDate != null) {
	hasCreationDate = true;
      }
      dout.writeBoolean(hasCreationDate);
      if (hasCreationDate) {
	byte[] dateBytes = marshaller.marshall(creationDate);
	dout.writeInt(dateBytes.length);
	dout.write(dateBytes);
      }
      
      writeStringToStream(sequenceIdentifier, dout);
      writeStringToStream(addressingIdentifier, dout);

      marshaller.writeEprToStream(source, dout);
      marshaller.writeEprToStream(destination, dout);

      dout.writeBoolean(isSource);

      dout.writeBoolean(hasWsrmSequencePolicies);
      if (hasWsrmSequencePolicies) {
	byte[] attachBytes = wsrmSequencePolicies.getBytes();
	dout.writeInt(attachBytes.length);
	dout.write(attachBytes);
      }

      dout.writeBoolean(hasLastMessageInfo);
      dout.writeLong(lastMessageNumber);

      dout.writeBoolean(isExpired);
      dout.writeBoolean(isTimedOut);
      dout.writeLong(timeOfLastActivity);
      dout.writeLong(timeoutTimestamp);

      dout.writeBoolean(isTerminated);
      if (isTerminated) {
	dout.writeLong(terminationTimestamp);
	writeStringToStream(terminationReason, dout);
      }
      marshalledBytes = baOutputStream.toByteArray();
    } catch (Exception ioe) {
      System.out.println(moduleName + "Error while marshalling" + ioe);
      
    } /** end try-catch block*/
    
    return marshalledBytes;
  }
  

   private void writeStringToStream(String toWrite, DataOutputStream dout) 
    throws IOException {
    if (toWrite == null) {
      dout.writeInt(0);
      return;
    }

    byte[] toWriteBytes = toWrite.getBytes();
    dout.writeInt(toWriteBytes.length);
    dout.write(toWriteBytes);
  }


  public WsrmSequenceInfoImpl(byte[] marshalledBytes) {
    ByteArrayInputStream baInputStream = 
      new ByteArrayInputStream(marshalledBytes);
    DataInputStream din = new DataInputStream(baInputStream);

    try {
      boolean hasCreationDate = din.readBoolean();
      if (hasCreationDate) {
	byte[] dateBytes = new byte[din.readInt()];
	din.readFully(dateBytes);
	creationDate = (Date) marshaller.unmarshall(dateBytes);
      }
      
      sequenceIdentifier   = readStringFromStream(din);
      addressingIdentifier = readStringFromStream(din);
      
      source = marshaller.readEprFromStream(din);
      destination = marshaller.readEprFromStream(din);

      isSource = din.readBoolean();

      hasWsrmSequencePolicies = din.readBoolean();
      if (hasWsrmSequencePolicies) {
	byte[] attachBytes =  new byte[din.readInt()];
	din.readFully(attachBytes);
	wsrmSequencePolicies = 
	  wsrmSequencePolicyFactory.getWsrmSequencePolicies(attachBytes);
      }
      
      
      hasLastMessageInfo = din.readBoolean();
      lastMessageNumber = din.readLong();
      
      isExpired  = din.readBoolean();
      isTimedOut = din.readBoolean();
      timeOfLastActivity = din.readLong();
      timeoutTimestamp = din.readLong();

      isTerminated = din.readBoolean();
      if (isTerminated) {
	terminationTimestamp = din.readLong();
	terminationReason = readStringFromStream(din);
      }
    } catch (Exception ioe) {
      System.out.println(moduleName + "Error while un-marshalling" + ioe);
      ioe.printStackTrace();
    }/** end try-catch block*/



  }

  private String readStringFromStream(DataInputStream din) 
    throws IOException {
    int numToRead = din.readInt(); 
    if (numToRead == 0) {
      return null;
    }
    
    byte[] toReadBytes = new byte[numToRead];
    din.readFully(toReadBytes);
    String readString = new String(toReadBytes);
    return readString;
  }

  public String toString() {
    String stringRep = "WsrmSequenceInfo ";

    stringRep += ("Creation Date=" + creationDate + ", SequenceIdentifier=" +
		  sequenceIdentifier + ", AddressingIdentifier=" +
		  addressingIdentifier + ", isSource=(" + isSource + ")");

    stringRep += (", Source=" + source + ", Destination=" +  destination);
    
    if (hasWsrmSequencePolicies) {
      stringRep += (" " + wsrmSequencePolicies );
    }

    if (hasLastMessageInfo) {
      stringRep += ( " LastMessage Number=" + lastMessageNumber);
    }

    stringRep += (" isExpired=(" + isExpired +") isTimedOut=(" + isTimedOut +
		  ") isTerminated=(" + isTerminated +")" );
    if (isTerminated) {
      stringRep += (" TerminationReason=" + terminationReason);
    }
    
    stringRep += (" timeOfLastActivity=" + timeOfLastActivity);
    return stringRep;
  }

}
